package com.watch.system.plugin.easyexcel;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mysql.cj.util.StringUtils;
import com.watch.system.common.base.IBaseEnum;
import com.watch.system.common.constant.SystemConstants;
import com.watch.system.common.enums.GenderEnum;
import com.watch.system.common.enums.StatusEnum;
import com.watch.system.converter.UserConverter;
import com.watch.system.model.entity.CarUser;
import com.watch.system.model.entity.SysRole;
import com.watch.system.model.entity.SysUser;
import com.watch.system.model.entity.SysUserRole;
import com.watch.system.model.query.CarUserPageQuery;
import com.watch.system.model.vo.CarAuthImportVO;
import com.watch.system.model.vo.CarUserImportVO;
import com.watch.system.model.vo.UserImportVO;
import com.watch.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 用户导入监听器
 * <p>
 *  <a href="https://easyexcel.opensource.alibaba.com/docs/current/quickstart/read#%E6%9C%80%E7%AE%80%E5%8D%95%E7%9A%84%E8%AF%BB%E7%9A%84%E7%9B%91%E5%90%AC%E5%99%A8">最简单的读的监听器</a>
 *
 * @author haoxr
 * @since 2022/4/10 20:49
 */
@Slf4j
public class UserAppImportListener extends MyAnalysisEventListener<CarUserImportVO> {


    // 有效条数
    private int validCount;

    // 无效条数
    private int invalidCount;

    // 导入返回信息
    StringBuilder msg = new StringBuilder();

    private final CarUserService userService;


    private  final AuthService authService;

    public UserAppImportListener() {
        this.userService = SpringUtil.getBean(CarUserService.class);
        this.authService = SpringUtil.getBean(AuthService.class);
    }

    /**
     * 每一条数据解析都会来调用
     * <p>
     * 1. 数据校验；全字段校验
     * 2. 数据持久化；
     *
     * @param userImportVO    一行数据，类似于 {@link AnalysisContext#readRowHolder()}
     * @param analysisContext
     */
    @Override
    public void invoke(CarUserImportVO userImportVO, AnalysisContext analysisContext) {
        log.info("解析到一条用户数据:{}", JSONUtil.toJsonStr(userImportVO));
        // 校验数据
        StringBuilder validationMsg = new StringBuilder();

        String username = userImportVO.getLoginName();
//        if (StrUtil.isBlank(username)) {
//            validationMsg.append("用户名为空；");
//        } else {
//            CarUserPageQuery queryParams=new CarUserPageQuery();
//            queryParams.setKeywords(username);
//            long count = userService.getUserPage(queryParams).getTotal();
//            if (count > 0) {
//                validationMsg.append("用户名已存在；");
//            }
//        }

        if (validationMsg.isEmpty()) {
            UUID uuid= UUID.randomUUID();
            String token = uuid.toString().replaceAll("-","");
            if (StrUtil.isBlank(username)) {
                userImportVO.setStatus("5");
                userImportVO.setRegDate(new Date());
            }
            userImportVO.setUserToken(token);
            boolean saveResult = userService.saveImport(userImportVO);

            if (saveResult) {
                if (!StrUtil.isBlank(userImportVO.getModel())) {
                    CarAuthImportVO carAdImportVO = new CarAuthImportVO();
                    carAdImportVO.setModel(userImportVO.getModel());
                    carAdImportVO.setBrandName(userImportVO.getBrandName());
                    carAdImportVO.setType("0");
                    carAdImportVO.setStatus("1");
                    carAdImportVO.setCreateDate(new Date());
                    carAdImportVO.setUserId(userImportVO.getUserId());
                    authService.saveAuthImport(carAdImportVO);
                }
                validCount++;
            } else {
                invalidCount++;
                msg.append("第").append(validCount + invalidCount).append("行数据保存失败；<br/>");
            }
        } else {
            invalidCount++;
            msg.append("第" + (validCount + invalidCount) + "行数据校验失败：").append(validationMsg + "<br/>");
        }
    }


    /**
     * 所有数据解析完成会来调用
     *
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }


    @Override
    public String getMsg() {
        // 总结信息
        String summaryMsg = StrUtil.format("导入用户结束：成功{}条，失败{}条；<br/>{}", validCount, invalidCount, msg);
        return summaryMsg;
    }
}
